package com.preparation.controller;

import com.preparation.domain.Category;
import com.preparation.dto.R;
import com.preparation.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/categories")
@CrossOrigin
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    // 增加类别
    @PostMapping
    public R addCategory( @RequestBody Category category) {
        return categoryService.addCategory(category);
    }

    // 删除类别
    @DeleteMapping("/{id}")
    public R deleteCategory(@PathVariable Integer id) {
        boolean result = categoryService.removeById(id);
        return result ? R.success("删除成功") : R.error();
    }

    // 修改类别
    @PutMapping
    public R updateCategory(@RequestBody Category category) {
        boolean result = categoryService.updateById(category);
        return result ? R.success("修改成功") : R.error();
    }

    // 根据ID查询类别
    @GetMapping("/{id}")
    public R getCategoryById(@PathVariable Integer id) {
        Category category = categoryService.getById(id);
        return category != null ? R.success(category, "查询成功") : R.error(404, "查询失败");
    }

    // 查询所有类别
    @GetMapping
    public R getAllCategories() {
        List<Category> categoryList = categoryService.list();
        return R.success(categoryList, "查询成功");
    }
}
